import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login/login.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/home',
    component: () => import('../views/Home/home.vue'),
    children: [
      { path: '/', name: 'welcom', component: () => import('../views/HelloWelcom/welcom.vue') },
      { path: '/users', name: 'users', component: () => import('../views/pages/userList/userList.vue') },
      { path: '/rights', name: 'permissions', component: () => import('../views/pages/Authority/permissions/permissions.vue') },
      { path: '/roles', name: 'roles', component: () => import('../views/pages/Authority/roles/roles.vue') },
      { path: '/categories', name: 'categories', component: () => import('../views/pages/Goods/categories.vue') },
      { path: '/params', name: 'params', component: () => import('../views/pages/Goods/params.vue') },
      { path: '/goods', name: 'goods', component: () => import('../views/pages/Goods/goods_list.vue') },
      { path: '/orders', name: 'order', component: () => import('../views/pages/Order/order.vue') },
      { path: '/reports', name: 'reports', component: () => import('../views/pages/Reports/reports.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 设置前置路由守卫阻止用户强行进入后台界面
router.beforeEach((to, from, next) => {
  // 1获取用户需要前往的 hash地址
  const hashPath = to.path
  // 获取token
  const token = window.sessionStorage.getItem('token')
  // 2判断用户是否具有token
  if (hashPath === '/home' && !token) return next('/login') // 3没有token跳转Login界面就行注册
  if (hashPath === '/login') return next()
  // 不是去后台界面就直接放行
  next()
})
export default router
